﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ideas2Realize.Data.Models;
using Ideas2Realize.Helpers;
using Ideas2Realize.Data.Business.Interface;

namespace Ideas2Realize.Controllers
{
    [Authorize()]
    public class ProposalController : BaseController
    {

        public JsonResult SaveFile(HttpPostedFileBase files)
        {
            throw new NotImplementedException();

            //string tmpname = Guid.NewGuid().ToString();
            //string extension = System.IO.Path.GetExtension(files.FileName);
            //string shortName = System.IO.Path.GetFileNameWithoutExtension(files.FileName); 
            //string temporaryFilename = string.Format("{0}{1}",tmpname, extension);
            //string filename = System.IO.Path.Combine(ConfigHelper.TemporaryUploadsPath, temporaryFilename);

            //files.SaveAs(filename);

            //return  Success(new { 
            //    filename = shortName, 
            //    temporaryFilename, 
            //    extension = extension.TrimStart(new char[] {'.'}) }
            //    , true);
        }

        [HttpPost()]
        public JsonResult SaveDraft(FormCollection collection, HttpPostedFileBase files)
        {
            try
            {
                Deviation dev = new Deviation();

                if (!string.IsNullOrEmpty(collection["Anonymous"]))
                {
                    dev.IsAnonymous = true;
                }
                else
                {
                    dev.IsAnonymous = false;
                }

                dev.DeviationType = (int)DeviationTypeEnum.Draft;
                dev.ProblemToSolve = collection["ProblemToSolve"];
                dev.Subject = collection["Subject"];
                dev.Solution = collection["MySolution"];

                dev.Created = DateTime.Now;
                dev.CreatedBy = User.Identity.Name;
                dev.Updated = DateTime.Now;
                dev.UpdatedBy = User.Identity.Name;

                DeviationRepository.Insert(dev);
                
                // add user to deviationusers.
                // get the users id and bind it to the deviation
                DeviationRepository.BindUser(new int[] { UserContext().UserId }, dev.Id);

                // save file . 
                if (files != null)
                {
                    // handle the single file that is attacted (for now).  
                    string extension = System.IO.Path.GetExtension(files.FileName);
                    string shortName = System.IO.Path.GetFileNameWithoutExtension(files.FileName);
                    int filesize = files.ContentLength;
                    string contenttype = files.ContentType;
                    byte[] buffer = FileHelper.ReadFully(files.InputStream);

                    UploadedFile file = new UploadedFile();
                    file.FileContent = buffer;
                    file.FileContentType = contenttype;
                    file.FileExtension = extension;
                    file.Filename = shortName;
                    file.Filesize = filesize;
                    file.DeviationId = dev.Id;
                    file.Insert();
                }


                return Success(dev, true);
            }
            catch (Exception ex)
            {
                return Error(ex, true);
            }
        
        }

        [HttpPost()]
        public JsonResult SaveAndSubmit(FormCollection collection, HttpPostedFileBase files)
        {

            /* 
             * TODO: 
             *  - Get users department by users id. 
             *  - Get head of department.
             *  - Set deviations next owner = cheif of users department.
             *  
             */

            try
            {
                Deviation dev = null;

                int? id = collection["Id"].ToNullableInt();

                if (id.HasValue && id.Value > 0) {
                   dev = DeviationRepository.GetById(id.Value);
                } else {
                   dev = new Deviation();
                }

                if (!string.IsNullOrEmpty(collection["Anonymous"]))
                {
                    dev.IsAnonymous = true;
                }
                else
                {
                    dev.IsAnonymous = false;
                }

                dev.DeviationType = (int)DeviationTypeEnum.Unhandled;
                dev.ProblemToSolve = collection["ProblemToSolve"];
                dev.Subject = collection["Subject"];
                dev.Solution = collection["MySolution"];

                dev.Created = DateTime.Now;
                dev.CreatedBy = User.Identity.Name;
                dev.Updated = DateTime.Now;
                dev.UpdatedBy = User.Identity.Name;

                if (dev.Id > 0)
                {
                    DeviationRepository.Update(dev, id.Value);
                }
                else
                {
                    DeviationRepository.Insert(dev);

                    // add user to deviationusers.
                    // get the users id and bind it to the deviation
                    DeviationRepository.BindUser(new int[] { UserContext().UserId }, dev.Id);
                }

                // The next owner of the deviation. 
                // get the users id and bind it to the deviation
                // DeviationRepository.BindUser(new int[] { UserContext().UserId }, dev.Id);

                // save file . 
                if (files != null)
                {
                    // handle the single file that is attacted (for now).  
                    string extension = System.IO.Path.GetExtension(files.FileName);
                    string shortName = System.IO.Path.GetFileNameWithoutExtension(files.FileName);
                    int filesize = files.ContentLength;
                    string contenttype = files.ContentType;
                    byte[] buffer = FileHelper.ReadFully(files.InputStream);

                    UploadedFile file = new UploadedFile();
                    file.FileContent = buffer;
                    file.FileContentType = contenttype;
                    file.FileExtension = extension;
                    file.Filename = shortName;
                    file.Filesize = filesize;
                    file.DeviationId = dev.Id;
                    file.Insert();
                }

                return Success(dev, true); 
            }
            catch (Exception ex)
            {
                return Error(ex, true);
            }

        }

        public XmlResult List(int limit, int page, string proposaltype)
        {

            DeviationTypeEnum dtId = DeviationTypeEnum.None;

             switch(proposaltype) {
             
                 case "Draft":

                     dtId = DeviationTypeEnum.Draft;

                     break; 

                 case "Unhandled":

                     dtId = DeviationTypeEnum.Unhandled;

                     break;

                 case "Pending":
                     dtId = DeviationTypeEnum.Pending;

                     break; 

                 case "Postponed":
                     dtId = DeviationTypeEnum.Postponed;

                     break; 
             }

             PetaPoco.Page<Ideas2Realize.Data.Models.DeviationsView> pagedObject = DeviationRepository.GetPagedView(limit, page,dtId, UserContext().UserId);

            return PagedResult<Ideas2Realize.Data.Models.DeviationsView>(pagedObject);
        }
        

        public XmlResult MyProposals() {

            List<proposaltreeitem> children = new List<proposaltreeitem>();

            var deviations = DeviationRepository.GetByUserId(UserContext().UserId);

            children.Add(new proposaltreeitem { id = "All", text = string.Format("All deviations ({0})",deviations.Count()), leaf = true });
            children.Add(new proposaltreeitem { id = "Draft", text = string.Format("Drafts ({0})", deviations.Where(p => p.DeviationType == (int)DeviationTypeEnum.Draft).Count()), leaf = true });
            children.Add(new proposaltreeitem { id = "Unhandled", text = string.Format("Unhandled ({0})", deviations.Where(p => p.DeviationType == (int)DeviationTypeEnum.Unhandled).Count()), leaf = true });
            children.Add(new proposaltreeitem { id = "Postponed", text = string.Format("Postponed ({0})", deviations.Where(p => p.DeviationType == (int)DeviationTypeEnum.Postponed).Count()), leaf = true });

            object result = new proposaltreeitem { text = "Root", id="root", children= children };

            return new XmlResult(result);
        }
    }

    public class proposaltreeitem
    {
        public proposaltreeitem() {
        }
        public string id { get; set; }
        public string text { get; set; }
        public List<proposaltreeitem> children { get; set; }
        public bool leaf { get; set; }
    }
}
